package bll

import (
	"auth/store/postgres"
	"context"

	"auth/event"
	"auth/model"
	"auth/model/entity"
	"auth/store"
)

type role struct {
	iRole store.IRole
}

var Role = &role{}

func (a *role) init() func() {
	a.iRole = postgres.Role
	return func() {}
}

func (a *role) onEvent(*event.Data) {}

func (a *role) Create(ctx context.Context, in *model.RoleCreateRequest) error {
	var (
		err error
	)

	c := buildRole(in)
	_, err = a.iRole.Create(c)
	return err
}

func (a *role) Update(ctx context.Context, in *model.RoleUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	dict["permission_ids"] = in.PermissionIds

	// do other update here

	return a.iRole.Update(in.ID, dict)
}

func (a *role) Delete(ctx context.Context, in *model.RoleDeleteRequest) error {
	return a.iRole.Delete(in.ID)
}

func (a *role) List(ctx context.Context, in *model.RoleListRequest) (*model.RoleListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.Role
		out   = &model.RoleListResponse{}
	)

	if total, list, err = a.iRole.List(in); err != nil {
		return nil, err
	}

	out.Total = total
	out.Data = model.RolesEntityToDto(list)

	return out, nil
}

func buildRole(in *model.RoleCreateRequest) *entity.Role {
	// todo: check the entity is required
	return &entity.Role{

		Name: in.Name,

		PermissionIds: in.PermissionIds,

		Type: 0,

		CreatedAt: 0,

		UpdatedAt: 0,
	}
}
